package com.xxwy.ddu.cms.authonrize.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xxwy.ddu.cms.authonrize.entity.Role;
import com.xxwy.ddu.cms.authonrize.entity.RoleAccess;
import com.xxwy.ddu.cms.authonrize.entity.UserRoles;
import com.xxwy.ddu.cms.authonrize.mapper.*;
import com.xxwy.ddu.cms.authonrize.service.IRoleService;
import com.xxwy.ddu.cms.authonrize.service.IUserRolesService;
import com.xxwy.ddu.cms.authonrize.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xxwy
 * @since 2018-08-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRolesMapper userRolesMapper;

    @Autowired
    RoleAccessMapper roleAccessMapper;


    @Transactional
    @Override
    public void delectUserWithRole(int rId) {
        //删除角色
        deleteById(rId);
        //删除用户
        EntityWrapper<UserRoles> wrapper = new EntityWrapper<>();
        wrapper.eq("r_Id", rId);
        List<UserRoles> userRoles = userRolesMapper.selectList(wrapper);
        if (userRoles != null && !userRoles.isEmpty()) {
            userRoles.forEach(x -> {
                //判断是否只有一个角色，是就删除
                Integer uId = x.getuId();
                EntityWrapper<UserRoles> selectCount = new EntityWrapper<>();
                selectCount.eq("u_id", uId);
                Integer integer = userRolesMapper.selectCount(selectCount);
                if (integer <= 1) {
                    userMapper.deleteById(uId);
                }
            });
            //删除角色用户表
            List<Integer> collect = userRoles.stream().map(UserRoles::getUrId).collect(Collectors.toList());
            if (collect != null&& !collect.isEmpty()) {
                deleteBatchIds(collect);
            }
        }
        //删除授权
        EntityWrapper<RoleAccess> roleAccessWrapper = new EntityWrapper<>();
        roleAccessWrapper.eq("r_Id", rId);
        roleAccessMapper.delete(roleAccessWrapper);
    }
}
